#!/bin/bash

name="MySQL-Proxy of $1"
proxydir=/usr/local/mysql-proxy
binfile="$proxydir/bin/mysql-proxy"
pidfile="$proxydir/log/$1.pid"
confile="$proxydir/conf/$1.cnf"

function start()
{
	ps -ef | grep "mysql-proxy --defaults-file=.*$1.cnf" | grep -v grep >/dev/null 2>&1

	if [ "$?" == "0" ]; then
		echo "error: $name is running now"
		exit 2
	else
		$binfile --defaults-file=$confile

		if [ "$?" == "0" ]; then
			echo "OK: $name is started"
		else
			echo "error: failed to start $name"
			exit 2
		fi
	fi
}

function stop()
{
	ps -ef | grep "mysql-proxy --defaults-file=.*$1.cnf" | grep -v grep >/dev/null 2>&1

	if [ "$?" == "0" ]; then
		ps -ef |  grep "mysql-proxy --defaults-file=.*$1.cnf" | grep -v grep | awk '{print $2}' | xargs kill -9 >/dev/null 2>&1

		if [ "$?" == "0" ]; then
			rm -f $pidfile
			echo "OK: $name is stopped"
		else
			echo "error: failed to stop $name"
			exit 3
		fi
	else
		echo "error: $name is NOT running"
		exit 3
	fi
}

function restart()
{
	stop $1
	start $1
}

function status()
{
	ps -ef | grep "mysql-proxy --defaults-file=.*$1.cnf" | grep -v grep >/dev/null 2>&1

	if [ "$?" == "0" ]; then
		ps -ef | grep "mysql-proxy --defaults-file=.*$1.cnf" | grep -v grep | awk '{print $2}' | while read proxy_pid; do
			echo "$name is running ($proxy_pid)"
		done
	else
		echo "$name is NOT running"
	fi
}

case $2 in
	"start")
		start $1
		;;  

	"stop")
		stop $1
		;;

	"restart")
		restart $1
		;;

	"status")
		status $1
		;;
	*)
		echo "Usage: $0 instance {start|stop|restart|status}"
		exit 1 
esac

exit 0
